package com.whiteape.book.ui.activity;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.whiteape.book.R;
import com.whiteape.book.contract.SearchContract;
import com.whiteape.book.model.bo.SearchResultBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.presenter.SearchPresenter;
import com.whiteape.book.ui.adapter.KeyWordAdapter;
import com.whiteape.book.ui.adapter.SearchBookAdapter;
import com.whiteape.book.ui.base.BaseMVPActivity;
import com.whiteape.book.utils.SoftKeyboardUtil;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.URLUtils;
import com.whiteape.book.widget.RefreshLayout;
import com.whiteape.book.widget.TagColor;
import com.whiteape.book.widget.TagGroup;
import com.whiteape.book.widget.itemdecoration.DividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


/**
 * Created by newbiechen on 17-4-24.
 */

public class SearchActivity extends BaseMVPActivity<SearchContract.Presenter>
        implements SearchContract.View {
    private static final String TAG = "SearchActivity";
    private static final int TAG_LIMIT = 8;

    @BindView(R.id.search_iv_back)
    ImageView mIvBack;
    @BindView(R.id.search_et_input)
    EditText mEtInput;
    @BindView(R.id.search_iv_delete)
    ImageView mIvDelete;
    @BindView(R.id.search_iv_search)
    ImageView mIvSearch;
    @BindView(R.id.search_book_tv_refresh_hot)
    TextView mTvRefreshHot;
    @BindView(R.id.search_tg_hot)
    TagGroup mTgHot;
    /*    @BindView(R.id.search_rv_history)
        RecyclerView mRvHistory;*/
    @BindView(R.id.refresh_layout)
    RefreshLayout mRlRefresh;
    @BindView(R.id.refresh_rv_content)
    RecyclerView mRvSearch;

    private KeyWordAdapter mKeyWordAdapter;
    private SearchBookAdapter mSearchAdapter;

    private boolean isTag;
    private List<String> mHotTagList = new ArrayList<>();
    private int mTagStart = 0;
    private String mCurrentSearchKey;
    private int usedSourceCount = 0;
    private int finishedSourceCount = 0;

    @Override
    protected int getContentId() {
        return R.layout.activity_search;
    }

    @Override
    protected SearchContract.Presenter bindPresenter() {
        return new SearchPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        setUpAdapter();
        mRlRefresh.setBackground(ContextCompat.getDrawable(this, R.color.white));
        mRlRefresh.setEmptyText("无结果，尝试多导入一些网源试试吧~");
    }

    private void setUpAdapter() {
        mKeyWordAdapter = new KeyWordAdapter();
        mSearchAdapter = new SearchBookAdapter();

        mRvSearch.setLayoutManager(new LinearLayoutManager(this));
        mRvSearch.addItemDecoration(new DividerItemDecoration(this));
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        //退出
        mIvBack.setOnClickListener(
                (v) -> onBackPressed()
        );

        //输入框
        mEtInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().equals("")) {
                    //隐藏delete按钮和关键字显示内容
                    if (mIvDelete.getVisibility() == View.VISIBLE) {
                        mIvDelete.setVisibility(View.INVISIBLE);
                        mRlRefresh.setVisibility(View.INVISIBLE);
                        //删除全部视图
                        mKeyWordAdapter.clear();
                        mSearchAdapter.clear();
                        mRvSearch.removeAllViews();
                    }
                    return;
                }
                //显示delete按钮
                if (mIvDelete.getVisibility() == View.INVISIBLE) {
                    mIvDelete.setVisibility(View.VISIBLE);
                    mRlRefresh.setVisibility(View.VISIBLE);
                    //默认是显示完成状态
                    mRlRefresh.showFinish();
                }
                //搜索
                String query = s.toString().trim();
                mCurrentSearchKey = query;
                if (isTag) {
                    mRlRefresh.showLoading();
                    mPresenter.searchBook(query);
                    isTag = false;
                } else {
                    //传递
                    mPresenter.searchKeyWord(query);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //键盘的搜索
        mEtInput.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //修改回车键功能
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    searchBook();
                    return true;
                }
                return false;
            }
        });

        //进行搜索
        mIvSearch.setOnClickListener(
                (v) -> searchBook()
        );

        //删除字
        mIvDelete.setOnClickListener(
                (v) -> {
                    mEtInput.setText("");
                    toggleKeyboard();
                }
        );

        //点击查书
        mKeyWordAdapter.setOnItemClickListener(
                (view, pos) -> {
                    //显示正在加载
                    mRlRefresh.showLoading();
                    String book = mKeyWordAdapter.getItem(pos);
                    mPresenter.searchBook(book);
//                    toggleKeyboard();
                    hideKeyboard();
                }
        );

        //Tag的点击事件
        mTgHot.setOnTagClickListener(
                tag -> {
                    isTag = true;
                    mEtInput.setText(tag);
                }
        );

        //Tag的刷新事件
        mTvRefreshHot.setOnClickListener(
                (v) -> refreshTag()
        );

        //书本的点击事件
        mSearchAdapter.setOnItemClickListener(
                (view, pos) -> {
                    CollectionMediaBean collectionMediaBean = new CollectionMediaBean();
                    SearchResultBo resultBean = mSearchAdapter.getItem(pos);


                    collectionMediaBean.setMediaType(resultBean.getMediaType());
                    collectionMediaBean.setAuthor(resultBean.getAuthor());
                    collectionMediaBean.setCoverUrl(resultBean.getCoverUrl());
                    collectionMediaBean.setId(resultBean.getDetailUrl());
                    collectionMediaBean.setCategory(resultBean.getCategory());
                    collectionMediaBean.setDesc(resultBean.getDesc());
                    collectionMediaBean.setLastChapter(resultBean.getLastChapter());
                    collectionMediaBean.setLastUpdated(resultBean.getLastUpdated());
                    collectionMediaBean.setState(resultBean.getState());
                    collectionMediaBean.setTitle(resultBean.getTitle());
                    collectionMediaBean.setWordCount(resultBean.getWordCount());
                    collectionMediaBean.setSiteSourceBean(resultBean.getSiteSourceBean());
                    collectionMediaBean.setVarMap(resultBean.getVarMap());
//                    collectionMediaBean.setBookSourceUrl();
//                    String bookId = mSearchAdapter.getItem(pos).get_id();
                    MediaDetailActivity.startActivity(this, collectionMediaBean, null);
//                    BookReadActivity.startActivity(SearchActivity.this, );
                }
        );
    }

    private void searchBook() {
        String query = mEtInput.getText().toString().trim();
        if (!query.equals("")) {
            mCurrentSearchKey = query;
            mSearchAdapter.clear();
            mRlRefresh.setVisibility(View.VISIBLE);
            mRlRefresh.showLoading();
            mPresenter.searchBook(query);
            //显示正在加载
            mRlRefresh.showLoading();

//            toggleKeyboard();
            hideKeyboard();
        }
    }

    private void hideKeyboard() {

        mEtInput.clearFocus();
        SoftKeyboardUtil.hideKeyboard(mEtInput);
    }

    private void toggleKeyboard() {

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    protected void startLogic() {
        super.startLogic();
        //默认隐藏
        mRlRefresh.setVisibility(View.GONE);

        String initSearchKey = getIntent().getStringExtra("searchKey");
        if (!StringUtils.isEmpty(initSearchKey)) {
            mEtInput.setText(initSearchKey);
            searchBook();
        }
        //获取热词
        mPresenter.searchHotWord();
    }

    @Override
    public void showError() {
    }

    @Override
    public void complete() {

    }

    @Override
    public void finishHotWords(List<String> hotWords) {
        mHotTagList = hotWords;
        refreshTag();
    }

    private void refreshTag() {
        if (mHotTagList.size() == 0) {
            //TODO 多次点击问题
            mPresenter.searchHotWord();
            return;
        }
        if (mHotTagList.size() <= TAG_LIMIT) {
            return;
        }
        int last = mTagStart + TAG_LIMIT;
        if (mHotTagList.size() <= last) {
//            mTagStart = 0;
            last = mHotTagList.size();
            List<String> tags = mHotTagList.subList(mTagStart, last);

            List<TagColor> colors = TagColor.getRandomColors(tags.size());
            String[] tagsArr = new String[tags.size()];
            mTgHot.setTags(colors, tags.toArray(tagsArr));
            mTagStart = 0;
            return;
        }
        List<String> tags = mHotTagList.subList(mTagStart, last);
        List<TagColor> colors = TagColor.getRandomColors(tags.size());
        String[] tagsArr = new String[tags.size()];
        mTgHot.setTags(colors, tags.toArray(tagsArr));
        mTagStart += TAG_LIMIT;
    }

    @Override
    public void finishKeyWords(List<String> keyWords) {
        if (keyWords.size() == 0) mRlRefresh.setVisibility(View.INVISIBLE);
        mKeyWordAdapter.refreshItems(keyWords);
        if (!(mRvSearch.getAdapter() instanceof KeyWordAdapter)) {
            mRvSearch.setAdapter(mKeyWordAdapter);
        }
    }

    @Override
    public void finishBooks(List<SearchResultBo> searchResultBos) {
        finishedSourceCount++;
        if (searchResultBos == null || searchResultBos.isEmpty()) {
            if (finishedSourceCount >= usedSourceCount && mSearchAdapter.getItemSize() == 0) {
                mRlRefresh.showEmpty();
            }
            return;
        }
        searchResultBos.get(0).getSiteSourceBean().getSiteHostUrl();
        for (SearchResultBo searchResultBo : mSearchAdapter.getItems()) {
            if (searchResultBo.getSiteSourceBean().getSiteHostUrl().equals(searchResultBos.get(0).getSiteSourceBean().getSiteHostUrl())) {
                //表示已经有这个网源的请求数据了，这个是重复数据
                return;
            }

        }

        //按照 标题+作者 来区分一个作品，然后这个作品，可以累加多个源
        int beforeSize = mSearchAdapter.getItemCount();
        for (SearchResultBo resultBo : searchResultBos) {
            if (resultBo.getTitle().trim().equals(mCurrentSearchKey)) {
                boolean hasUpdated = false;
                for (int i = 0; i < mSearchAdapter.getItemCount(); i++) {
                    SearchResultBo adapterData = mSearchAdapter.getItem(i);
                    if (!adapterData.getTitle().equals(mCurrentSearchKey)) {
                        break;
                    }
                    //相同类型（小说、漫画）而且作者相同的
                    if (adapterData.getSiteSourceBean().getSiteType() == resultBo.getSiteSourceBean().getSiteType() &&
                            adapterData.getAuthor().equals(resultBo.getAuthor())) {
                        if (StringUtils.isEmpty(adapterData.getCoverUrl()) && !StringUtils.isEmpty(resultBo.getCoverUrl())) {
                            adapterData.setCoverUrl(URLUtils.getAbsolutePath(resultBo.getSiteSourceBean().getSiteHostUrl(), resultBo.getCoverUrl()));
                        }
                        if (adapterData.getBackupSiteSourceList() == null) {
                            adapterData.setBackupSiteSourceList(new ArrayList<>());
                        }
                        adapterData.getBackupSiteSourceList().add(resultBo.getSiteSourceBean());
                        hasUpdated = true;
                        mSearchAdapter.notifyItemChanged(i);
                    }
                }
                if (!hasUpdated) {
                    mSearchAdapter.addItem(0, resultBo);
                }

            } else {
                mSearchAdapter.addItem(resultBo);
            }
        }
        mSearchAdapter.notifyItemRangeChanged(beforeSize, mSearchAdapter.getItemCount() - beforeSize);

        mRlRefresh.showFinish();
//        if ( mSearchAdapter.getItemSize() == 0) {
////            mRlRefresh.showEmpty();
//            mRlRefresh.showFinish();
//        } else {
//            //显示完成
//            mRlRefresh.showFinish();
//        }
        //加载
        if (!(mRvSearch.getAdapter() instanceof SearchBookAdapter)) {
            mRvSearch.setAdapter(mSearchAdapter);
        }


    }

    @Override
    public void errorBooks() {
//        mRlRefresh.showEmpty();
        finishedSourceCount++;
        if (finishedSourceCount >= usedSourceCount && mSearchAdapter.getItemSize() == 0) {
            mRlRefresh.showEmpty();
        }
    }

    @Override
    public void onBackPressed() {
        if (mRlRefresh.getVisibility() == View.VISIBLE) {
            mEtInput.setText("");
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void setUsedSourceCount(int count) {
        finishedSourceCount = 0;
        usedSourceCount = count;
    }
}
